package com.jnu.bookkeep.ui.home;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.jnu.bookkeep.Data.Bill;
import com.jnu.bookkeep.Data.DataStorage;
import com.jnu.bookkeep.EditBillActivity;
import com.jnu.bookkeep.R;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment {

    private List<Bill> billList;
    private HomeFragment.MyRecycleViewAdapter BillAdapter;
    private DataStorage dataStorage;

    public HomeFragment() {
        // Required empty public constructor
    }

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        //billList = new ArrayList<>();

        View rootView = inflater.inflate(R.layout.fragment_home, container, false);
        initData();
        RecyclerView recyclerView = rootView.findViewById(R.id.MoneyView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this.getContext());
        recyclerView.setLayoutManager(linearLayoutManager);
        BillAdapter = new HomeFragment.MyRecycleViewAdapter(billList);
        recyclerView.setAdapter(BillAdapter);

        FloatingActionButton floatingActionButton = rootView.findViewById(R.id.add_item);
        floatingActionButton.setOnClickListener(view -> {
            Intent intent = new Intent(HomeFragment.this.getContext(), EditBillActivity.class);
            intent.putExtra("position", billList.size());
            launcherAdd.launch(intent);
        });

        return rootView;
    }

    private void initData() {
        dataStorage = new DataStorage(this.getContext());
        billList = dataStorage.loadData();
    }

    ActivityResultLauncher<Intent> launcherAdd = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            int resultCode = result.getResultCode();
            if(resultCode == 111){
                Intent data = result.getData();
                assert data != null;
                float price = Float.parseFloat(data.getStringExtra("price"));      //传到界面可以是字符串..后续优化
                String mark = data.getStringExtra("mark");
                String date = data.getStringExtra("date");
                int billType = data.getIntExtra("billType",0);
                int typeSignal = data.getIntExtra("typeSignal",R.drawable.others);
                int position = data.getIntExtra("position",0);

                String type_class;
                switch (typeSignal){
                    case R.drawable.eat:
                        type_class = "饮食";
                        break;
                    case R.drawable.daily_use:
                        type_class = "日用";
                        break;
                    case R.drawable.accommodation:
                        type_class = "住宿";
                        break;
                    case R.drawable.travel:
                        type_class = "出行";
                        break;
                    case R.drawable.others:
                        type_class = "其他";
                        break;
                    default:
                        type_class = " ";
                }

                if(billType == 0){
                    price = 0 - price;
                }
                billList.add(position,new Bill(mark,type_class,date,price,typeSignal));
                dataStorage.SaveData();
                BillAdapter.notifyItemInserted(position);
            }
        }
    });

    ActivityResultLauncher<Intent> launchEdit = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            int resultCode = result.getResultCode();
            if(resultCode == 111){
                Intent data = result.getData();
                assert data != null;
                float price = Float.parseFloat(data.getStringExtra("price"));      //传到界面可以是字符串..后续优化
                String mark = data.getStringExtra("mark");
                String date = data.getStringExtra("date");
                int billType = data.getIntExtra("billType",0);
                int typeSignal = data.getIntExtra("typeSignal",R.drawable.others);
                int position = data.getIntExtra("position",0);

                String type_class;
                switch (typeSignal){
                    case R.drawable.eat:
                        type_class = "饮食";
                        break;
                    case R.drawable.daily_use:
                        type_class = "日用";
                        break;
                    case R.drawable.accommodation:
                        type_class = "住宿";
                        break;
                    case R.drawable.travel:
                        type_class = "出行";
                        break;
                    case R.drawable.others:
                        type_class = "其他";
                        break;
                    default:
                        type_class = " ";
                }

                if(billType == 0){
                    price = 0 - price;
                }
                billList.get(position).setAmount(price);
                billList.get(position).setDate(date);
                billList.get(position).setRemark(mark);
                billList.get(position).setResourceId(typeSignal);
                billList.get(position).setType(type_class);

                dataStorage.SaveData();
                BillAdapter.notifyItemChanged(position);
            }
        }
    });

    private class MyRecycleViewAdapter extends RecyclerView.Adapter{

        private final List<Bill> bills;

        private MyRecycleViewAdapter(List<Bill> bills) {
            this.bills = bills;
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.bill_item, parent, false);

            return new HomeFragment.MyRecycleViewAdapter.ViewHolder(itemView);
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            HomeFragment.MyRecycleViewAdapter.ViewHolder Holder = (HomeFragment.MyRecycleViewAdapter.ViewHolder)holder;

            float price = bills.get(position).getAmount();
            if(price >= 0){
                Holder.getPriceView().setTextColor(Color.GREEN);
            }
            else if(price < 0){
                Holder.getPriceView().setTextColor(Color.RED);
            }

            Holder.getDateView().setText(bills.get(position).getDate());
            Holder.getImageView().setImageResource(bills.get(position).getResourceId());
            Holder.getMarkView().setText(bills.get(position).getRemark());
            Holder.getPriceView().setText(String.valueOf(price));
            Holder.getTypeTextView().setText(bills.get(position).getType());
        }

        @Override
        public int getItemCount() {
            return bills.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {


            ImageView imageView;
            TextView typeTextView;
            TextView markView;
            TextView dateView;
            TextView priceView;

            public ImageView getImageView() {
                return imageView;
            }

            public TextView getTypeTextView() {
                return typeTextView;
            }

            public TextView getMarkView() {
                return markView;
            }

            public TextView getDateView() {
                return dateView;
            }

            public TextView getPriceView() {
                return priceView;
            }

            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                this.dateView = itemView.findViewById(R.id.date_view);
                this.imageView = itemView.findViewById(R.id.type_image);
                this.markView = itemView.findViewById(R.id.mark_view);
                this.priceView = itemView.findViewById(R.id.price_view);
                this.typeTextView = itemView.findViewById(R.id.type_text);

                itemView.setOnCreateContextMenuListener(this);
            }

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                int position = getAdapterPosition();

                switch (item.getItemId()) {
                    case 1:
                        addBill(position);
                        break;
                    case 2:
                        editBill(position);
                        break;
                    case 3:
                        deleteBill(position);
                        break;
                }
                Toast.makeText(HomeFragment.this.getContext(), "点击" + item.getTitle(), Toast.LENGTH_LONG).show();
                return false;
            }

            private void deleteBill(int position) {
                billList.remove(position);
                dataStorage.SaveData();
                HomeFragment.MyRecycleViewAdapter.this.notifyItemRemoved(position);
            }

            private void editBill(int position) {

                Intent intent = new Intent(HomeFragment.this.getContext(), EditBillActivity.class);

                float price = billList.get(position).getAmount();
                int billType = 1;
                if(price<0)        //为0的话..
                {
                    price = 0 - price;
                    billType = 0;
                }
                String date = billList.get(position).getDate();
                String[] s = date.split("-");
                int year = Integer.parseInt(s[0]);
                int month = Integer.parseInt(s[1]);
                int day = Integer.parseInt(s[2]);

                intent.putExtra("position", position);
                intent.putExtra("mark",billList.get(position).getRemark());
                intent.putExtra("billType",billType);
                intent.putExtra("price",price);
                intent.putExtra("typeSignal",billList.get(position).getResourceId());
                intent.putExtra("year",year);
                intent.putExtra("month",month);
                intent.putExtra("day",day);

                launchEdit.launch(intent);
            }

            private void addBill(int position) {
                Intent intent = new Intent(HomeFragment.this.getContext(), EditBillActivity.class);
                intent.putExtra("position", position);
                launcherAdd.launch(intent);
            }

            @Override
            public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
                MenuItem menuItemAdd = contextMenu.add(Menu.NONE, 1, 1, "Add");
                MenuItem menuItemEdit = contextMenu.add(Menu.NONE, 2, 2, "Edit");
                MenuItem menuItemDelete = contextMenu.add(Menu.NONE, 3, 3, "Delete");

                menuItemAdd.setOnMenuItemClickListener(this);
                menuItemEdit.setOnMenuItemClickListener(this);
                menuItemDelete.setOnMenuItemClickListener(this);
            }
        }
    }
}